<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import TodoSidebar from '../components/todo/TodoSidebar.vue'
import TodoInput from '../components/todo/TodoInput.vue'
import TodoList from '../components/todo/TodoList.vue'
import TodoBatchBar from '../components/todo/TodoBatchBar.vue'

const router = useRouter()

const currentUserName = ref(localStorage.getItem('todo_currentUser') || '')


interface Task {
  id: number
  message: string
  isCompleted: boolean
  category: string
  selected?: boolean  
  isEditing?: boolean  
  editTemp?: string 
}
const items = ref<Task[]>([]) 
const activeCategory = ref('全部')
const categories = ref(['全部', '日常', '学习', '工作', '旅行'])
const newTaskCategory = ref('日常')

// 加载/保存任务
const getStorageKey = () => `todo_tasks_${currentUserName.value}`
const loadTasks = (): Task[] => {
  try {
    const raw = localStorage.getItem(getStorageKey())
    return raw ? JSON.parse(raw) : []
  } catch (err) {
    console.error('加载任务失败:', err)
    return []
  }
}
const saveTasks = () => {
  try {
    localStorage.setItem(getStorageKey(), JSON.stringify(items.value))
  } catch (err) {
    console.error('保存任务失败:', err)
  }
}


const filteredTasks = computed(() =>
  items.value.filter(t => activeCategory.value === '全部' || t.category === activeCategory.value)
)
const activeTodos = computed(() => filteredTasks.value.filter(t => !t.isCompleted))
const completedTodos = computed(() => filteredTasks.value.filter(t => t.isCompleted))
const allSelected = computed({
  get: () => filteredTasks.value.length > 0 && filteredTasks.value.every(t => t.selected),
  set: val => {
    const filteredIds = filteredTasks.value.map(t => t.id)
    items.value.forEach(t => { if (filteredIds.includes(t.id)) t.selected = val })
  }
})
const selectedList = computed(() => items.value.filter(t => t.selected))
const hasCompletedSelected = computed(() => selectedList.value.some(t => t.isCompleted))

const switchCategory = (category: string) => {
  activeCategory.value = category
  if (category !== '全部') newTaskCategory.value = category
}
const addTodo = (msg: string) => {
  items.value.push({ id: Date.now(), message: msg, isCompleted: false, category: newTaskCategory.value })
}
const updateNewTaskCategory = (val: string) => newTaskCategory.value = val
const toggleComplete = (id: number) => {
  const task = items.value.find(i => i.id === id)
  if (task) task.isCompleted = !task.isCompleted
}
const removeTodo = (id: number) => items.value = items.value.filter(i => i.id !== id)
const startEdit = (task: Task) => { task.isEditing = true; task.editTemp = task.message }
const saveEdit = (task: Task) => {
  const newMsg = task.editTemp?.trim()
  if (newMsg) task.message = newMsg
  task.isEditing = false; task.editTemp = ''
}
const cancelEdit = (task: Task) => { task.isEditing = false; task.editTemp = '' }
const updateTaskSelected = (taskId: number, isSelected: boolean) => {
  const task = items.value.find(t => t.id === taskId)
  if (task) task.selected = isSelected
}
const completeSelected = () => {
  selectedList.value.forEach(t => { t.isCompleted = true; t.selected = false })
}
const deleteSelected = () => items.value = items.value.filter(t => !t.selected)

const handleLogout = () => {
  localStorage.removeItem('todo_currentUser')
  currentUserName.value = ''
  items.value = []
  router.push('/login') 
}

onMounted(() => {
  if (currentUserName.value) {
    items.value = loadTasks()
  } else {
    router.push('/login')
  }
  watch(items, saveTasks, { deep: true })
})
</script>

<template>
  <div class="todo-page">
    <TodoSidebar
      :current-user-name="currentUserName"
      :active-todos-length="activeTodos.length"
      :categories="categories"
      :active-category="activeCategory"
      @logout="handleLogout"
      @switch-category="switchCategory"
    />
    
    <main class="main-content">
      <TodoInput
        :new-task-category="newTaskCategory"
        :categories="categories.filter(c => c !== '全部')"
        :filtered-tasks-length="filteredTasks.length"
        :all-selected="allSelected"
        @add-todo="addTodo"
        @update-category="updateNewTaskCategory"
        @update-all-selected="(val) => { allSelected = val }"
      />
      <TodoList
        :active-todos="activeTodos"
        :completed-todos="completedTodos"
        @toggle-complete="toggleComplete"
        @remove-todo="removeTodo"
        @start-edit="startEdit"
        @save-edit="saveEdit"
        @cancel-edit="cancelEdit"
        @update-task-selected="updateTaskSelected"
      />
    </main>

    <TodoBatchBar
      v-if="selectedList.length"
      :selected-list="selectedList"
      :has-completed-selected="hasCompletedSelected"
      @complete-selected="completeSelected"
      @delete-selected="deleteSelected"
    />
  </div>
</template>